//
//  WBTitleButton.swift
//  个人微博
//
//  Created by 任聪聪 on 2018/1/4.
//  Copyright © 2018年 任孜聪. All rights reserved.
//

import UIKit

/// 自定义UIbutton来设置首页标题按钮，实现标题在上下箭头前面
class WBTitleButton: UIButton {
    //重载按钮的初始化方法
    //实现title是否为nil，如果title为nil设置标题为首页如果不为空设置为用户昵称
     init(title:String?) {
       super.init(frame: CGRect())
        //1.判断title是否为nil
        if title == nil {
            setTitle("首页", for: [])
        }else {
            //2.用用户昵称来设置标题
            setTitle(title!+" ", for: [])
            //设置按钮图片
            setImage(UIImage(named:"navigationbar_arrow_down"), for: [])
            setImage(UIImage(named:"navigationbar_arrow_up"), for: .selected)
        }
        //3.设置标题字体颜色
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray, for: [])
        //4.设置标题位置
        sizeToFit()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //重新布局子视图
    override func layoutSubviews() {
        guard let titleLabel = titleLabel,let imageView = imageView else {
            return
        }
        //一定要构造父类方法否则显示有问题
        super.layoutSubviews()
        //1.将titleLabel的x向左移动imageView的宽度
        titleLabel.frame = titleLabel.frame.offsetBy(dx:-imageView.bounds.width, dy: 0)
        //2.将imageView的x向右移动titleLabel的宽度
        imageView.frame = imageView.frame.offsetBy(dx:titleLabel.bounds.width, dy: 0)
        print("宽度\(imageView.bounds.width)")
    }
}
